package com.appcenter.application.service;

import com.appcenter.application.dto.jobusers.JobUserDto;
import com.appcenter.application.dto.orgJobs.GetOrgJobsDto;
import com.appcenter.application.dto.orgs.OrgDto;
import com.appcenter.application.dto.users.UserDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.input.app.GetAppsInput;
import com.appcenter.application.input.org.GetOrgsInput;
import com.appcenter.application.input.orgJob.*;
import com.appcenter.application.mapper.*;
import com.appcenter.application.model.*;
import com.appcenter.application.output.orgJob.*;
import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.appcenter.jz.unit.ObjectUnit;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

import static org.apache.http.util.TextUtils.isBlank;
import static tk.mybatis.mapper.entity.Example.*;

@Service
public class OrgJobService {
    @Autowired
    OrgJobsMapper orgJobsMapper;

    @Autowired
    JobUsersMapper jobUsersMapper;
    @Autowired
    AppsMapper appsMapper;
    @Autowired
    OrgsMapper orgsMapper;
    @Autowired
    OrgService orgService;
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    ObjectFinal objectFinal;

//    @Transactional
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 加载岗位人员关系
     *  时间: 2019/4/26 13:55 
     *  参数: 
     */
    public PageLoadOutput PageLoad(PageLoadInput input){
        try {
            PageLoadOutput output = new PageLoadOutput();
            Map<String, OrgDto> parentOrgDtoDic = new HashMap<String, OrgDto>();

            GetAppsInput getAppsInput=new GetAppsInput();
            //List<Apps> apps = appsMapper.SearchApps(getAppsInput);


            GetOrgsInput orgsInput=new GetOrgsInput();
            orgsInput.setAppCode(input.getAppCode());
            List<OrgDto> orgDtos =orgService.GetOrgs(orgsInput).getOrgs();

          //  GetOrgJobsOutput searchOrgJobListOutput=GetOrgJobs(input);
            //output.setApps(apps);
            output.setOrgs(orgDtos);

            List<GetOrgJobsDto> getOrgJobsDto=new ArrayList <>();
            output.setItems(new PagedResult<GetOrgJobsDto>(getOrgJobsDto, getOrgJobsDto.size()));
          //  output.setItems(searchOrgJobListOutput.getItems());
            return output;
        }catch (Exception e) {
            throw new ErrorJsonResult("1010203123", e.toString());
        }
    }

//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 加载部门岗位关系
     *  时间: 2019/4/26 13:55 
     *  参数: 
     */
    public GetOrgJobsOutput GetOrgJobs(GetOrgJobsInput input) throws Exception {
        GetOrgJobsOutput output=new GetOrgJobsOutput();
        if (isBlank(input.getAppCode()))
            input.setAppCode(null);
        if (!isBlank(input.getOrgId())) {
            Example exampleOrg = new Example(Orgs.class);
            Criteria criteria = exampleOrg.createCriteria();
            criteria.andEqualTo("id", input.getOrgId());
            criteria.andEqualTo("versionNo",objectFinal.getDataEffectiveVersion());
            Orgs org=orgsMapper.selectOneByExample(exampleOrg);
            if (org!=null) {
                input.setOrgIdPath(org.getOrgIdPath());
            }else {
                input.setOrgIdPath(null);
            }
        }
        else{
            input.setOrgIdPath(null);
        }
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "Id desc");
        List<GetOrgJobsDto>  ls=orgJobsMapper.GetOrgJobs(input);
        PageInfo<GetOrgJobsDto> page = new PageInfo<>(ls);
        List<GetOrgJobsDto> getOrgJobsDto=page.getList();
        for(GetOrgJobsDto orgJob: getOrgJobsDto)
        {
           List<UserDto> users= orgJobsMapper.GetUsersByOrgJobId(orgJob.getId(),input.getVersionNo());
            orgJob.setUsers(users);
        }
        output.setItems(new PagedResult<GetOrgJobsDto>(getOrgJobsDto, (int) page.getTotal()));
        return output;
    }

//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 创建部门岗位关系
     *  时间: 2019/4/26 13:55 
     *  参数: 
     */
    public CreateOrgJobOutput CreateOrgJob(CreateOrgJobInput input) throws Exception {
        CreateOrgJobOutput output=new  CreateOrgJobOutput();
        Example exampleOrgJob = new Example(OrgJobs.class);
        Criteria criteria = exampleOrgJob.createCriteria();
        criteria.andEqualTo("jobId", input.getItem().getJobId());
        criteria.andEqualTo("orgId", input.getItem().getOrgId());
        int countOrgJob= orgJobsMapper.selectCountByExample  (exampleOrgJob);
        if (countOrgJob > 0) {
            throw new ErrorJsonResult("1000031", "部门下已存在岗位！");
        }
        //添加部门岗位关联
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        input.getItem().setId(uuid);
        input.getItem().setCreateUserId(CurrentUser.getUserId());
        input.getItem().setCreateTime(new Date());
       // input.getItem().setVersionNo(objectFinal.getDataEffectiveVersion());;
        OrgJobs orgJob=new OrgJobs();
//        ObjectUnit.Copy(input.getItem(),orgJob);
        BeanUtils.copyProperties(input.getItem(),orgJob);
        orgJobsMapper.insertSelective(orgJob);
        //添加部门人员关联
        if (input.getItem().getJobUsers()!=null) {
            for (JobUserDto jobUserDto : input.getItem().getJobUsers()) {
                uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                input.getItem().setId(uuid);
                jobUserDto.setId(uuid);
                jobUserDto.setCreateTime(new Date());
                jobUserDto.setCreateUserId(CurrentUser.getUserId());
                JobUsers jobUser = new JobUsers();
                BeanUtils.copyProperties(jobUserDto, jobUser);
                jobUsersMapper.insertSelective(jobUser);
            }
        }
        output.setItem(input.getItem());
        return output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 修改部门岗位关系
     *  时间: 2019/4/26 13:56 
     *  参数: 
     */
    public EditOrgJobOutput EditOrgJob(EditOrgJobInput input) throws Exception {
        EditOrgJobOutput output=new EditOrgJobOutput();
        if(!isBlank(input.getItem().getId()))
        {
            OrgJobs orgJob = orgJobsMapper.selectByPrimaryKey(input.getItem().getId());
            orgJobsMapper.DeleteJobUserById(input.getItem().getJobId());
            if (orgJob!=null) {
                if (input.getItem().getJobUsers()!=null) {
                    for (JobUserDto jobUserDto : input.getItem().getJobUsers()) {
                      String  uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                        input.getItem().setId(uuid);
                        jobUserDto.setId(uuid);
                        jobUserDto.setCreateTime(new Date());
                        jobUserDto.setCreateUserId(CurrentUser.getUserId());
                        JobUsers jobUser = new JobUsers();
                        BeanUtils.copyProperties(jobUserDto, jobUser);
                        jobUsersMapper.insertSelective(jobUser);
                    }
                }
            }
        }
        output.setItem(input.getItem());
        return output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 删除部门岗位关系
     *  时间: 2019/4/26 14:06
     *  参数: 
     */
    public DeleteOrgJobOutput DeleteOrgJob(DeleteOrgJobInput input) throws Exception {
        DeleteOrgJobOutput output=new DeleteOrgJobOutput();
        if(!isBlank(input.getItem().getId()))
        {
            orgJobsMapper.deleteByExample(input.getItem().getId());
            orgJobsMapper.DeleteJobUserById(input.getItem().getJobId());
        }
        output.setItem(input.getItem());
        return output;
    }
}
